<template>
  <div>
    <!-- 顶部按钮区域 -->
    <div class="top-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入商品名称"
        class="search-input"
        clearable
      />
      <el-select v-model="sortOrder" placeholder="排序" class="sort-select">
        <el-option label="价格升序" value="asc"></el-option>
        <el-option label="价格降序" value="desc"></el-option>
      </el-select>
      <el-button type="primary" @click="selectBuyRecord">查看购买记录</el-button>
    </div>

    <!-- 视图切换按钮 -->
    <div class="view-toggle">
      <el-button @click="toggleView" :type="viewMode === 'list' ? 'primary' : 'default'">列表模式</el-button>
      <el-button @click="toggleView" :type="viewMode === 'grid' ? 'primary' : 'default'">卡片模式</el-button>
    </div>

    <!-- 卡片视图 -->
    <div class="card-container" v-if="viewMode === 'grid'">
      <el-card v-for="(item, index) in sortedItems" :key="index" class="product-card">
        <div class="image-container">
          <img :src="item.coverpicture || defaultImage" class="card-image" />
        </div>
        <div class="product-info">
          <p class="product-name">{{ item.pname }}</p>
          <p class="product-price">{{ item.price }}￥</p>
          <p class="product-description">{{ item.description || '暂无描述' }}</p>
          <p class="product-stock">库存：{{ item.stock }} 件</p>
          <el-button type="success" plain @click="handleBuy(item.pid, item.pname, item.fid)">购买</el-button>
        </div>
      </el-card>
    </div>

    <!-- 列表视图 -->
    <div class="list-container" v-else>
      <el-table :data="sortedItems" border>
        <el-table-column prop="pname" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="价格" sortable></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
      </el-table>
    </div>

    <!-- 购买记录弹窗 -->
    <el-dialog title="购买记录" :visible.sync="showRecordDialog" width="50%" center>
      <div v-if="purchaseRecords.length > 0">
        <el-card v-for="(record, index) in purchaseRecords" :key="index">
          <p>商品名称: {{ record.pname }}</p>
          <p>购买时间: {{ record.buytime }}</p>
        </el-card>
      </div>
      <p v-else style="text-align: center;">暂无购买记录</p>
    </el-dialog>

    <!-- 购买成功弹窗 -->
    <el-dialog
      title="购买成功"
      :visible.sync="isPurchased"
      width="30%"
      center
      @close="closeModal"
    >
      <p>{{ purchaseMessage }}</p>
    </el-dialog>
  </div>
</template>

<script>
import { selectAllproduct, handleBuy, selectBuyRecord } from '@/api/market.ts';

export default {
  data() {
    return {
      searchQuery: '',  // 搜索框输入
      products: [],     // 商品数据
      sortOrder: 'asc', // 排序方式

      // 购买记录弹窗
      showRecordDialog: false,
      purchaseRecords: [],

      // 购买成功提醒
      isPurchased: false,
      purchaseMessage: "",

      isFarmProduct: false,  // 是否农贸产品
      defaultImage: 'https://via.placeholder.com/250x200?text=Product+Image', // 默认图片

      // 当前视图模式（列表模式或卡片模式）
      viewMode: 'grid',  // 默认是列表视图
    };
  },
  computed: {
    // 商品筛选
    filteredItems() {
      const searchQuery = this.searchQuery.trim().toLowerCase();
      return this.products.filter(item => item.pname.toLowerCase().includes(searchQuery));
    },

    // 根据价格排序后的商品
    sortedItems() {
      return this.filteredItems.sort((a, b) => {
        if (this.sortOrder === 'asc') {
          return a.price - b.price;
        } else {
          return b.price - a.price;
        }
      });
    },
  },
  methods: {
    // 购买商品
    async handleBuy(pid, pname, fid, category) {
      const uid = JSON.parse(localStorage.getItem('currentUser')).uid;
      const param = { uid, pid, fid, pname };

      if (category === '农贸产品') {
        this.isFarmProduct = true;
        this.purchaseMessage = `您正在购买农贸产品: ${pname}`;
      } else {
        this.isFarmProduct = false;
        this.purchaseMessage = `我成功购买了${pname}`;
      }

      try {
        await handleBuy(param);
        this.isPurchased = true;
        this.fetchProducts(); // 购买成功后刷新商品数据
      } catch (error) {
        console.error("购买失败:", error);
      }
    },

    // 关闭购买弹窗
    closeModal() {
      this.isPurchased = false;
      this.isFarmProduct = false;
    },

    // 获取商品数据
    async fetchProducts() {
      try {
        const response = await selectAllproduct();
        if (response?.data?.data && Array.isArray(response.data.data)) {
          this.products = response.data.data;
        } else {
          console.error("商品数据格式错误:", response);
        }
      } catch (error) {
        console.error("获取商品数据失败:", error);
      }
    },

    // 获取购买记录
    async selectBuyRecord() {
      const uid = JSON.parse(localStorage.getItem('currentUser')).uid;
      try {
        const response = await selectBuyRecord(uid);
        this.purchaseRecords = (response?.data?.data || []).sort((a, b) => new Date(b.buytime) - new Date(a.buytime));
      } catch (error) {
        console.error("获取购买记录失败:", error);
      }
      this.showRecordDialog = true;
    },

    // 切换视图模式
    toggleView() {
      this.viewMode = this.viewMode === 'list' ? 'grid' : 'list';
    },
  },
  mounted() {
    this.fetchProducts();
  },
};
</script>

<style scoped>
.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.sort-select {
  width: 150px;
  margin-left: 20px;
}

.view-toggle {
  margin-bottom: 10px;
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  width: 250px;
  box-sizing: border-box;
}

.image-container {
  height: 200px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-image {
  width: 100%;
  object-fit: cover;
}

.product-info {
  padding: 10px;
  text-align: center;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-price {
  font-size: 14px;
  color: #e53935;
  margin-bottom: 5px;
}

.product-description {
  font-size: 12px;
  color: #757575;
  margin-bottom: 10px;
}

.product-stock {
  font-size: 12px;
  color: #388e3c;
}

.list-container {
  margin-top: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.footer-button {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
